'use strict';

const {
	Controller
} = require('uni-cloud-router');
const dbcmd = uniCloud.database().command;
const $ = dbcmd.aggregate;

module.exports = class GoodsController extends Controller {
	// 订单列表
	async goodsList() {
		const response = {
			code: 1,
			total: 0,
			datas: []
		};

		let {
			page,
			rows,
			group,
			orderby,
			state,
			name,
			cid
		} = this.ctx.data;

		const whereObj = {};

		// 状态
		if (state != '全部') {
			whereObj.state = state;
		}

		// 名称
		if (name) {
			whereObj.name = new RegExp(this.service.utils.filterRegexpKey(name), 'i');
		}
		// 分类
		if (cid) {
			whereObj.cid = cid;
		}

		// 分组状态数量
		let groupWhereObj = Object.assign({}, whereObj);
		delete groupWhereObj[group.field];

		const groupRes = await this.db.collection('usemall-goods')
			.aggregate()
			.match(groupWhereObj)
			.group({
				_id: '$' + group.field,
				cnt: $.sum(1)
			})
			.end();

		if (groupRes && groupRes.data) {
			response.groupDatas = groupRes.data;
			group.datas = [];
			group.total = 0;

			for (let key in group.obj) {
				group.obj[key] = 0;
			}

			response.groupDatas.forEach(x => {
				if (Object.keys(group.obj).includes(x._id + "")) {
					group.obj[x._id] = x.cnt;
					group.total += x.cnt;
				}
			})
			if (Object.keys(group.obj).includes('全部')) {
				group.obj['全部'] = group.total;
			}

			for (let key in group.obj) {
				group.datas.push({
					name: key,
					cnt: group.obj[key]
				})
			}
			response.group = group;
		}

		// 总数
		const countRes = await this.db.collection('usemall-goods').where(whereObj).count();
		response.total = countRes.total;

		// 排序
		orderby = orderby.split(' ');

		const res = await this.db.collection('usemall-goods')
			.where(whereObj)
			.orderBy(orderby[0], orderby[1])
			.field({
				sort: true,
				img: true,
				name: true,
				name_pw: true,
				is_vip: true,
				vip_price: true,
				price: true,
				market_price: true,
				limited: true,
				hot: true,
				sale_cnt: true,
				visit_cnt: true,
				collect_cnt: true,
				share_cnt: true,
				tags: true,
				state: true
			})
			.skip((page - 1) * rows)
			.limit(rows)
			.get();

		response.code = 0;
		response.datas = res.data;
		return response;
	}

	// 添加商品
	async add() {
		let response = {
			code: 1,
		};

		// 数据验证
		this.validate(this.ctx.data);

		let {
			goods,
			detail,
			skus
		} = this.ctx.data;

		// 限时精选、热门推荐 排序
		goods.limited_sort = goods.sort;
		goods.hot_sort = goods.sort;

		// 商品基本值
		goods.name = goods.name ? goods.name + '' : '';
		goods.name_pw = goods.name_pw ? goods.name_pw + '' : '';

		// 是否填写商品分享设置
		goods.share_title = goods.share_title ? goods.share_title + '' : goods.name;
		goods.share_img = goods.share_img || goods.img;
		goods.share_desc = goods.share_desc ? goods.share_desc + '' : goods.name_pw;

		// 商品默认值
		const goods_id = new Date().getTime() + (Math.round(Math.random() * 1000000) + '').padStart(6, '0');
		goods._id = goods_id;
		goods.stock_wh_num = goods.stock_num;
		goods.create_time = new Date().getTime();
		goods.create_uid = this.ctx.auth.uid;
		goods.create_uname = this.ctx.auth.userInfo.username || this.ctx.auth.userInfo.nickname;
		// 写入商品数据
		const goodsRes = await this.db.collection('usemall-goods').add(goods);

		// 商品详情默认值
		detail.goods_id = goods_id;
		detail.create_time = new Date().getTime();
		detail.create_uid = this.ctx.auth.uid;
		detail.create_uname = this.ctx.auth.userInfo.username || this.ctx.auth.userInfo.nickname;
		// 商品SKU默认值
		skus.forEach(x => {
			x._id = goods_id + '_' + x.goods_sku;
			x.goods_id = goods_id;
			x.img = x.img || goods.img;
			x.imgObj = x.imgObj || goods.imgs[0];
			x.stock_wh_num = x.stock_num;
			x.limit = goods.limit;

			x.create_time = new Date().getTime();
			x.create_uid = this.ctx.auth.uid;
			x.create_uname = this.ctx.auth.userInfo.username || this.ctx.auth.userInfo.nickname;
		});

		// 写入商品详情数据
		await this.db.collection('usemall-goods-detail').add(detail);
		if (skus.length > 0) {
			// 写入商品SKU数据
			await this.db.collection('usemall-goods-sku').add(skus);
		}

		response.code = 0;
		response.msg = '操作成功';

		return response;
	}
	// 验证请求数据
	validate(req) {
		if (!req) this.throw('请求参数不存在');
		if (!req.goods) this.throw('商品参数不存在');
		if (!req.detail) this.throw('商品详情参数不存在');

		if (!req.goods.name) this.throw('商品名称必填');
		if (!req.goods.cid) this.throw('请选择商品分类');
		if (req.goods.price <= 0) this.throw('商城价格不能小于0');
		if (!req.goods.img) this.throw('请上传商品主图');
	}

	// 获取商品数据
	async detail() {
		let response = {
			code: 1,
			goods: {},
			goods_detail: {},
			skus: [],
		};

		let start = new Date().getTime();
		const {
			goods_id
		} = this.ctx.data;

		// 产品数据
		let goods = await this.db.collection('usemall-goods').doc(goods_id).get();

		if (!goods || goods.data.length <= 0) {
			response.msg = `当前产品不存在`;
			return response;
		}

		const detail = await this.db.collection('usemall-goods-detail')
			.where({
				goods_id: goods_id
			})
			.get();
		const skus = await this.db.collection('usemall-goods-sku')
			.where({
				goods_id: goods_id
			})
			.get();

		response.goods = goods.data[0];
		response.goods_detail = detail.data[0];
		response.skus = skus.data;

		let end = new Date().getTime();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;
	}

	// 编辑商品
	async edit() {
		let response = {
			code: 1,
		};

		// 数据验证
		this.validate(this.ctx.data);

		let {
			goods_id,
			goods,
			detail,
			skus
		} = this.ctx.data;
		console.log('this.ctx.data', this.ctx.data);
		try {

			// 产品数据
			let __goods = await this.db.collection('usemall-goods').doc(goods_id).get();

			if (!__goods || __goods.data.length <= 0) {
				response.msg = `当前产品不存在`;
				return response;
			}

			// 限时精选、热门推荐 排序
			goods.limited_sort = goods.sort;
			goods.hot_sort = goods.sort;

			// 商品基本值
			goods.name = goods.name ? goods.name + '' : '';
			goods.name_pw = goods.name_pw ? goods.name_pw + '' : '';

			// 是否填写商品分享设置
			goods.share_title = goods.share_title ? goods.share_title + '' : goods.name;
			goods.share_img = goods.share_img || goods.img;
			goods.share_desc = goods.share_desc ? goods.share_desc + '' : goods.name_pw;

			// 商品默认值
			goods.last_modify_time = new Date().getTime();
			goods.last_modify_uid = this.ctx.auth.uid;
			goods.last_modify_uname = this.ctx.auth.userInfo.username || this.ctx.auth.userInfo.nickname;

			delete goods._id;
			// 写入商品数据
			const goodsRes = await this.db.collection('usemall-goods').doc(goods_id).update(goods);

			// 商品详情默认值
			detail.last_modify_time = new Date().getTime();
			detail.last_modify_uid = this.ctx.auth.uid;
			detail.last_modify_uname = this.ctx.auth.userInfo.username || this.ctx.auth.userInfo.nickname;
			// 商品SKU默认值
			skus.forEach(x => {
				x._id = goods_id + '_' + x.goods_sku;
				x.goods_id = goods_id;
				x.img = x.img || goods.img;
				x.imgObj = x.imgObj || goods.imgs[0];
				x.stock_wh_num = x.stock_num;
				x.limit = goods.limit;

				x.create_time = new Date().getTime();
				x.create_uid = this.ctx.auth.uid;
				x.create_uname = this.ctx.auth.userInfo.username || this.ctx.auth.userInfo.nickname;
			});

			// 写入商品详情数据
			await this.db.collection('usemall-goods-detail').where({
				goods_id: goods_id
			}).update(detail);

			// 删除商品SKU数据
			await this.db.collection('usemall-goods-sku').where({
				goods_id: goods_id
			}).remove();
			if (skus && skus.length > 0) {
				// 写入商品SKU数据
				await this.db.collection('usemall-goods-sku').add(skus);
			}

			response.code = 0;
			response.msg = '操作成功';

		} catch (e) {
			//TODO handle the exception
			console.log('catch', e);
		}
		return response;
	}

	// 商品删除
	async goodsRemove() {
		let response = {
			code: 1,
			msg: '',
			datas: null
		};

		let {
			id
		} = this.ctx.data;

		// 查询商品
		const goodsRes = await this.db.collection('usemall-goods').doc(id).get();
		const [goods] = goodsRes.data;

		if (goods.state == '销售中') {
			response.msg = '当前商品销售中，不可删除';
			return response;
		}

		try {
			await this.goodsRemoveService(id, goods);
		} catch (err) {
			response.msg = `当前商品${err.message}`;
			return response;
		}

		response.msg = '删除成功';
		response.code = 0;
		return response;
	}

	// 商品批量删除
	async goodsRemoves() {
		let response = {
			code: 1,
			msg: '',
			datas: null
		};

		let {
			ids
		} = this.ctx.data;

		// 查询商品
		const goodsRes = await this.db.collection('usemall-goods').where({
			_id: dbcmd.in(ids)
		}).get();

		let errs = [];
		for (let i = 0; i < goodsRes.data.length; i++) {
			let goods = goodsRes.data[i];
			if (goods.state == '销售中') {
				errs.push({
					msg: `[${goods.name}]商品销售中，不可删除`
				});
				continue;
			}

			try {
				// 删除商品
				await this.goodsRemoveService(goods._id, goods);
			} catch (err) {
				errs.push({
					msg: `[${goods.name}]商品[${err.message}]`
				});
				continue;
			}
		}

		if (!errs.length) {
			response.msg = '删除成功';
			response.code = 0;
		}
		response.datas = errs;
		return response;
	}

	// 删除商品
	async goodsRemoveService(id, goods) {
		// 查询限时拼团
		const groupbuyRes = await this.db.collection('usemall-market-groupbuy').where({
			goods_id: id
		}).get();

		for (let i = 0; i < groupbuyRes.data.length; i++) {
			let groupbuy = groupbuyRes.data[i];

			// 当前时间大于开始时间小于结束时间 在活动中
			if (Date.now() > groupbuy.group_begin_time && Date.now() < groupbuy.group_end_time) {
				this.throw('拼团活动中，不可删除');
			}

			// 根据拼团id 查询订单数据
			let orderRes = await this.db.collection('usemall-market-groupbuy').where({
				group_id: groupbuy._id
			}).field({
				state: true
			}).get();

			for (let o = 0; o < orderRes.data.length; o++) {
				let order = orderRes.data[o];

				if (order.state == '待成团') {
					this.throw('拼团已有用户参团，不可删除');
				}
			}
		}

		// 查询限时秒杀
		const seckillRes = await this.db.collection('usemall-market-seckill').where({
			goods_ids: id
		}).get();

		for (let i = 0; i < seckillRes.data.length; i++) {
			let seckill = seckillRes.data[i];

			// 当前时间大于开始时间小于结束时间 在活动中
			if (Date.now() > seckill.seckill_begin_time && Date.now() < seckill.seckill_end_time) {
				this.throw('秒杀活动中，不可删除');
			}
		}

		// 查询优惠券
		const couponRes = await this.db.collection('usemall-marketing-coupon-rule').where({
			allow_ids: id,
			allow_jsons: dbcmd.elemMatch({
				_id: id
			})
		}).get();

		for (let i = 0; i < couponRes.data.length; i++) {
			let coupon = couponRes.data[i];

			if (['运营中', '待激活'].includes(coupon.state)) {
				if (coupon.state == '待激活' && coupon.allow_ids.length == 1) {
					// 删除优惠券
					await this.db.collection('usemall-marketing-coupon-rule').doc(coupon._id).remove();
				} else {
					// 删除优惠券相关商品
					await this.db.collection('usemall-marketing-coupon-rule').doc(coupon._id).update({
						allow_ids: dbcmd.pull(id),
						allow_jsons: dbcmd.pull({
							_id: id
						})
					});
				}
			}
		}

		// 删除限时拼团
		for (let i = 0; i < groupbuyRes.data.length; i++) {
			let groupbuy = groupbuyRes.data[i];

			await this.db.collection('usemall-market-groupbuy').doc(groupbuy._id).remove();
		}

		for (let i = 0; i < seckillRes.data.length; i++) {
			let seckill = seckillRes.data[i];

			if (seckill.goods_ids.length == 1) {
				// 删除限时秒杀
				await this.db.collection('usemall-market-seckill').doc(seckill._id).remove();
			} else {
				// 删除限时秒杀关联商品
				await this.db.collection('usemall-market-seckill').doc(seckill._id).update({
					goods_ids: dbcmd.pull(id),
					goods_objs: dbcmd.pull({
						_id: id
					})
				});
			}
		}

		// 删除商品详情
		await this.db.collection('usemall-goods-detail').where({
			goods_id: id
		}).remove();

		// 删除商品sku
		await this.db.collection('usemall-goods-sku').where({
			goods_id: id
		}).remove();

		// 删除商品评价
		await this.db.collection('usemall-goods-comment').where({
			goods_id: id
		}).remove();

		// 删除商品
		await this.db.collection('usemall-goods').doc(id).remove();
	}

	// 商品分类删除
	async classifyRemove() {
		let response = {
			code: 1,
			msg: '',
			datas: null
		};

		let {
			id
		} = this.ctx.data;

		try {
			const goodsRes = await this.db.collection('usemall-goods').where({
				cids: id
			}).get();

			if (!goodsRes.data.length) {
				await this.db.collection('usemall-goods-category').doc(id).remove();
				response.msg = '删除成功';
				response.code = 0;
			} else {
				response.msg = '此分类存在商品，不可删除';
				response.code = 100;
			}
		} catch (err) {
			response.msg = err.message;
			response.code = 500;
		}

		return response;
	}
}